package conf

import (
	"crypto/ecdsa"
	"encoding/json"
	"io"
	"os"

	"github.com/PicoChain/accounts/abi"
	"github.com/PicoChain/common"
	"github.com/PicoChain/crypto"
)

type ConfigParams struct {
	Contracts  []*ContractParams `json:"contracts"`
	Chain      *ChainParams      `json:"chain"`
	ListenAddr string            `json:"listen_addr"`
}

func ReadConfig(path string) *ConfigParams {
	//open file
	file, err := os.Open(path)
	if err != nil {
		panic("read file error")
	}

	//decode file
	var config *ConfigParams
	if err := json.NewDecoder(file).Decode(&config); err != nil {
		panic("load config error")
	}
	return config
}

type ContractParams struct {
	Verion  string `json:"version"`
	Name    string `json:"name"`
	AbiPath string `json:"abi_file"`
	Addr    string `json:"addr"`
	Number  uint64 `json:"height"`
}

func (c *ContractParams) ContractVersion() string {
	return c.Verion
}
func (c *ContractParams) ContractName() string {
	return c.Name
}
func (c *ContractParams) ABIFile() abi.ABI {
	//read and storage contract abi
	f, err := os.Open(c.AbiPath)
	if err != nil {
		panic("invaild abi file")
	}
	parsed, err := abi.JSON(io.Reader(f))
	if err != nil {
		panic("invaild abi format")
	}
	return parsed
}
func (c *ContractParams) ContractAddr() common.Address {
	return common.HexToAddress(c.Addr)
}
func (c *ContractParams) Height() uint64 {
	return c.Number
}

type ChainParams struct {
	Key       string   `json:"poolkey"`
	ChargeKey string   `json:"chargekey"`
	Nodes     []string `json:"rpcURL"`
}

func (c *ChainParams) PoolKey() *ecdsa.PrivateKey {
	key, err := crypto.HexToECDSA(c.Key)
	if err != nil {
		panic("invaild pool account")
	}
	return key
}
func (c *ChainParams) ChargeAccKey() *ecdsa.PrivateKey {
	key, err := crypto.HexToECDSA(c.ChargeKey)
	if err != nil {
		panic("invaild pool account")
	}
	return key
}
func (c *ChainParams) NodesURL() []string {
	return c.Nodes
}
